package com.dmw.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.dmw.reggie.common.BaseContext;
import com.dmw.reggie.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否已经完成登录
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    // 路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 1. 获取本次请求的 URI
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String requestURI = req.getRequestURI();
        
        // 2. 定义能够直接放行的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };
        
        // 3. 判断本次请求是否需要放行
        boolean check = check(urls, requestURI);

        // 4. 放行
        if(check){
            filterChain.doFilter(req, resp);
            return;
        }

        // 5. 判断登录状态，如果已登录，则直接放行
        // 获取登录员工用户id
        Long empId = (Long) req.getSession().getAttribute("employee");
        if(empId != null){
            // 通过封装 ThreadLocal 的 BaseContext 保存用户id
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(req, resp);
            return;
        }

        // 获取登录顾客用户id
        Long userId = (Long) req.getSession().getAttribute("user");
        if(userId != null){
            // 通过封装 ThreadLocal 的 BaseContext 保存用户id
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(req, resp);
            return;
        }

        // 6. 如果未登录则返回登录结果，通过输出流方式向客户端页面响应数据
        resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls 可以放行的路径
     * @param requestURI 请求路径
     * @return
     */
    public static boolean check(String[] urls, String requestURI){
        for(String url: urls){
            if(PATH_MATCHER.match(url, requestURI)){
                return true;
            }
        }
        return false;
    }
}
